package tech.eyao.hs60x.user.controller;

import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import cn.jpush.api.push.model.PushPayload;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import tech.eyao.hs60x.common.CommonConstants;
import tech.eyao.hs60x.common.ConstantsKey;
import tech.eyao.hs60x.common.ReturnCode;
import tech.eyao.hs60x.dto.BaseResult;
import tech.eyao.hs60x.model.domain.AccountDO;
import tech.eyao.hs60x.model.domain.AccountRelationDO;
import tech.eyao.hs60x.service.AccountRelationService;
import tech.eyao.hs60x.service.AccountService;
import tech.eyao.hs60x.service.HealthService;
import tech.eyao.hs60x.service.LbsService;
import tech.eyao.hs60x.utils.JPushUtils;
import tech.eyao.hs60x.utils.TokenUtils;

@RequestMapping("/report")
@RestController
@Api("上报信息")
public class ReportContoller {

    private static final Logger    logger           = LoggerFactory.getLogger(ReportContoller.class);

    private static final int       ELECTRICITY_NUM  = 20;

    private static final int       DEFAULT_SETP_NUM = 0;
    @Autowired
    private LbsService             lbsService;
    @Autowired
    private HealthService          healthService;
    @Autowired
    private StringRedisTemplate    template;
    @Autowired
    private AccountRelationService accountRelationService;
    @Autowired
    private AccountService         accountService;

    @SuppressWarnings("static-access")
    @PostMapping("/info.do")
    @ApiOperation(value = "上传手表信息")
    public BaseResult info(@ApiParam("经度") double longitude, @ApiParam(value = "纬度") double latitude,
                           @ApiParam("步数") @RequestParam(value = "step", defaultValue = "0") Integer stepNumber,
                           @ApiParam("电量 10% 传10") @RequestParam(value = "electricity", defaultValue = "0") int electricity,
                           @ApiParam(value = "精度") @RequestParam(value = "accuracy", defaultValue = "0") int accuracy,
                           @ApiParam(value = "定位类型") int type,
                           @ApiParam(value = "地址1") @RequestParam(value = "address1", defaultValue = "") String address1,
                           @ApiParam(value = "地址2") @RequestParam(value = "address2", defaultValue = "") String address2,
                           @ApiParam(value = "上传GPS时间") @RequestParam(value = "uploadGpsTimesTamp", defaultValue = "") long uploadGpsTimesTamp) {
        BaseResult baseResult = new BaseResult();
        try {

            logger.info(
                    "ReportContoller info watchId={}, electricity={}, address1 = {}, address2 = {},uploadGpsTimesTamp={}",
                    TokenUtils.getUserId(), electricity, address1, address2, uploadGpsTimesTamp);
            AccountDO accountDO = accountService.getAccountById(TokenUtils.getUserId());

            if (null == accountDO) {
                baseResult.isBussinessFail("账户不存在！");
            }

            if (longitude > CommonConstants.ZERO && latitude > CommonConstants.ZERO) {
                lbsService.insert(TokenUtils.getUserId(), longitude, latitude, accuracy, type, address1, address2,
                        uploadGpsTimesTamp);
            }

            if (stepNumber > DEFAULT_SETP_NUM) {
                healthService.uploadStepNumber(TokenUtils.getUserId(), stepNumber);
            }

            if (electricity > 0) {
                // 缓存电量
                template.opsForValue().set(ConstantsKey.getWatchElectricitKey(TokenUtils.getUserId()),
                        String.valueOf(electricity));
                // 电量低于20% 提醒
                if (electricity <= ELECTRICITY_NUM) {
                    String adminAccountId = template.opsForValue()
                            .get(ConstantsKey.getWatchAdminKey(TokenUtils.getUserId()));
                    if (StringUtils.isEmpty(adminAccountId)) {
                        AccountRelationDO accountRelationDO = accountRelationService.getAccountAdminByWatchId(TokenUtils.getUserId());
                        if (null != accountRelationDO) {
                            adminAccountId = String.valueOf(accountRelationDO.getRelationId());
                        }
                    }
                    // 频率一小时通知一次
                    if (StringUtils.isNotEmpty(adminAccountId) && null == template.opsForValue()
                            .get(ConstantsKey.getUserElectricityNotification(adminAccountId))) {
                        PushPayload pushPayload = JPushUtils.buildPushObject_all_alias_alert(adminAccountId,
                                String.format("宝贝%s设备电量不足", StringUtils.defaultString(accountDO.getNickName())));
                        JPushUtils.getPhoneInstance().sendPush(pushPayload);
                        template.opsForValue().set(ConstantsKey.getUserElectricityNotification(adminAccountId), "1",
                                CommonConstants.ELECTRICITY_TIME_OUT, TimeUnit.SECONDS);
                    }
                }
            }
            baseResult.code = ReturnCode.C_SUCCESS_CODE;
            baseResult.message = ReturnCode.SUCCESS_CODE.getDesc();
        } catch (Exception e) {
            logger.error("[LbsController uploadWatchLbs error.]", e);
        }
        return baseResult;
    }
}
